<?php

namespace Beerus\Modules\BrandActivity\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel;
use Biz\model\brand\Brand;
use Biz\model\brandActivity\BrandActivityBasic;
use Biz\model\brandRights\BrandRightsAll;
use Biz\model\brandRights\BrandRightsSource;
use Biz\service\BrandActivity\BrandActivityService;
use Biz\service\BrandRights\BrandRightsSourceService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;

class IndexController extends Controller
{
    public const  PAGE_SIZE = 20;

    /**
     * 获取列表
     * @param Request $request
     * @param Content $content
     * @return Content
     */
    public function index(Request $request, Content $content): Content
    {
        $request_data = $request->all();
        $condition = self::getCondition($request_data);
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        $where = $condition;
        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        $list['list'] = BrandActivityService::index($where);
        unset($where['LIMIT']);
        $list['total'] = BrandActivityBasic::count($where);
        $gridModel = new GridDataModel($list['list'], $list['total'], [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) {
                    // 在这里添加字段过滤器
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('brand_id', '品牌ID')->placeholder('品牌ID');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('basic_id', 'BASIC_ID')->placeholder('BASIC_ID');
                        $filter->equal('activity_type', '活动类型')->select(BrandActivityBasic::ACTIVITY_NAME);
                    });
                    $filter->expand();//默认展开
                });
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableCreateButton();
                $grid->disableActions();
                $grid->column('id', '主键ID');
                $grid->column('activity_id', '活动ID');
                $grid->column('activity_type', '活动类型')->using(BrandActivityBasic::ACTIVITY_NAME);
                $grid->column('brand_id', '品牌ID');
                $grid->column('activity_name', '活动名称');
                $grid->column('basic_id', 'BASIC_ID');
            }
        );
        $tab = new Tab();
        $tab->add('活动列表', $grid->render(), true);
        $tab->addLink('活动权益', url('admin/brandActivity/rights'));
        $content->row($tab);

        return $content
            ->header('活动列表')
            ->description(' ')
            ->breadcrumb(['text' => '活动列表', 'url' => '/brandActivity/index']);
    }

    /**
     * @param $request
     * @return array
     */
    private static function getCondition($request): array
    {
        $condition['ORDER'] = ['id' => 'DESC'];
        if (isset($request['activity_type']) && !empty($request['activity_type'])) {
            $condition['activity_type'] = $request['activity_type'];
        }
        if (isset($request['basic_id']) && !empty($request['basic_id'])) {
            $condition['basic_id'] = $request['basic_id'];
        }
        if (isset($request['id']) && !empty($request['id'])) {
            $condition['id'] = $request['id'];
        }
        if (isset($request['brand_id']) && !empty($request['brand_id'])) {
            $condition['brand_id'] = $request['brand_id'];
        }

        return $condition;

    }

    public function rights(Request $request, Content $content): Content
    {
        $tab = new Tab();
        $tab->addLink('活动列表', url('admin/brandActivity/index'));

        $link_url = url('/admin/BrandRights/brandSource');
        $buttonLink = '<div class="btn-group download" style="margin-right: 10px">
            <a class="btn btn-sm btn-primary" target="_self" href="' . $link_url . '">
            <i class="fa fa-download"></i>
            <span class="hidden-xs">查看活动权益</span></a>
        </div>';

        $url = url('/admin/brandActivity/rights/export');
        $button = '<div class="btn-group download" style="margin-right: 10px">
            <a class="btn btn-sm btn-primary" target="_blank" href="' . $url . '">
            <i class="fa fa-download"></i>
            <span class="hidden-xs">导出活动权益</span></a>
        </div>';

        $tab->add('活动权益', $buttonLink . $button, true);

        $content->row($tab);
        return $content
            ->header('品牌活动权益')
            ->description(' ')
            ->breadcrumb(['text' => '品牌活动权益', 'url' => '/brandActivity/rights']);
    }


    public function exportRights(Request $request)
    {

        $activityRightsIds = BrandRightsSourceService::getAllSource('id',
            ['type' => [BrandRightsSource::TYPE_ACT, BrandRightsSource::TYPE_COMBINATION]]);
        $now = time();
        $where['rights_source_id'] = $activityRightsIds;
        $where['rights_status'] = BrandRightsAll::STATUS_ON;
        $where['start_time[<]'] = $now;
        $where['end_time[>=]'] = $now;
        $where['ORDER'] = [
            'brand_id' => 'ASC'
        ];
        $list = BrandRightsAll::selectList($where);

        $brandIds = array_column($list, 'brand_id');
        $brandIds = array_unique($brandIds);
        $brandList = Brand::getBrandListByIds($brandIds);
        $rightsSourceMap = BrandRightsSourceService::getRightsSourceMap([]);

        $data = [];
        foreach ($list as $row) {
            if (isset($brandList[$row['brand_id']])) {
                $data[] = [
                    'brand_id' => $row['brand_id'],
                    'brand_name' => $brandList[$row['brand_id']]['brand_name'],
                    'rights_source_id' => $row['rights_source_id'],
                    'rights_name' => $rightsSourceMap[$row['rights_source_id']] ? $rightsSourceMap[$row['rights_source_id']]['rights_title'] : '',
                    'total_num' => $row['total_num'],
                    'rights_num' => $row['rights_num'],
                    'date' => date('Y-m-d H:i:s', $row['start_time']) . '至' . date('Y-m-d H:i:s', $row['end_time']),
                ];
            }
        }

        $title = ['品牌id', '品牌名称', '权益id', '权益名称', '权益总次数', '权益剩余次数', '权益有效期'];

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $titCol = 'A';
        foreach ($title as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValue($titCol . '1', $value);
            $titCol++;
        }
        $sheet->getColumnDimension('A')->setWidth(12);
        $sheet->getColumnDimension('B')->setWidth(15);
        $sheet->getColumnDimension('C')->setWidth(12);
        $sheet->getColumnDimension('D')->setWidth(25);
        $sheet->getColumnDimension('E')->setWidth(12);
        $sheet->getColumnDimension('F')->setWidth(12);
        $sheet->getColumnDimension('G')->setWidth(35);
        $row = 2; // 从第二行开始
        foreach ($data as $item) {
            $dataCol = 'A';
            foreach ($item as $value) {
                // 单元格内容写入
                $sheet->setCellValue($dataCol . $row, $value);
                $dataCol++;
            }
            $row++;
        }
        $fileName = '品牌活动权益次数.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
        exit;

    }

}